package com.example.forwardmessages


import android.Manifest
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.net.wifi.WifiManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Telephony
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
import javax.mail.*
import javax.mail.internet.*
import android.text.format.Formatter
import android.util.Log
import android.widget.Toast
import android.os.Build
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.forwardmessages.databinding.FragmentFirstBinding
import com.example.forwardmessages.MIUIPermissionHelper
import com.example.forwardmessages.NotificationHelper
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkRequest

/**
 * A simple [Fragment] subclass as the default destination in the navigation.
 */
class FirstFragment : Fragment(), SmsRefreshCallback {

    private var _binding: FragmentFirstBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    // 权限请求码
    private val READ_SMS_PERMISSION_REQUEST_CODE = 100
    private val POST_NOTIFICATIONS_PERMISSION_REQUEST_CODE = 101
    
    // Notification helper for error logging and notifications
    private lateinit var notificationHelper: NotificationHelper

    // 短信列表
    private lateinit var smsList: MutableList<SmsMessage>

    // 适配器
    private lateinit var smsAdapter: SmsAdapter
    private var webServer: WebServer? = null
    private val SERVER_PORT = 8080
    private val TAG = "FirstFragment"

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentFirstBinding.inflate(inflater, container, false)
        return binding.root
    }
    
    
    


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        // Initialize notification helper
        notificationHelper = NotificationHelper(requireContext())
        super.onViewCreated(view, savedInstanceState)

        // 初始化RecyclerView
        initRecyclerView()

        // 设置按钮点击事件，用于请求权限
        binding.buttonFirst.setOnClickListener {
            requestSmsPermission()
        }

        // 设置刷新按钮点击事件
        binding.refreshButton.setOnClickListener {
            if (hasSmsPermission()) {
                loadSmsMessages()
            } else {
                Toast.makeText(context, "请先授予读取短信权限", Toast.LENGTH_SHORT).show()
            }
        }
        
        // 设置发送邮件按钮点击事件
        binding.emailButton.setOnClickListener {
            // 当用户手动点击发送邮件时，使用默认的SIM卡信息
            sendEmailWithSmtp("手动发送")
        }
        
        // 设置模拟短信接收按钮点击事件
        binding.simulateSmsButton.setOnClickListener {
            simulateSmsReception()
        }

        // 检查是否已有权限，如果有则直接加载短信
        if (hasSmsPermission()) {
            loadSmsMessages()
        }
        
        // 请求通知权限（Android 13+需要）
        requestNotificationPermission()
        
        // 初始化并启动Web服务器
        setupWebServer()
    }

    /**
     * 在Fragment恢复时重新检查权限并加载短信
     * 适用于从权限设置页面返回应用的情况
     */
    override fun onResume() {
        super.onResume()
        if (hasSmsPermission()) {
            loadSmsMessages()
        }
        
        // 更新Web服务器状态显示
        updateServerStatusDisplay()
    }

    private fun setupWebServer() {
        try {
            // 检查网络权限
            val hasInternetPermission = ContextCompat.checkSelfPermission(
                requireContext(),
                Manifest.permission.INTERNET
            ) == PackageManager.PERMISSION_GRANTED
            
            if (!hasInternetPermission) {
                binding.webServerStatusTextView.text = "缺少网络权限\nWeb服务器无法启动"
                return
            }
            
            // 创建并启动Web服务器
            webServer = WebServer(requireContext(), SERVER_PORT)
            // 设置短信刷新回调
            webServer?.setSmsRefreshCallback(this)
            
            // 延迟更新状态显示，确保服务器有足够时间启动
            Handler(Looper.getMainLooper()).postDelayed({
                updateServerStatusDisplay()
            }, 500)
        } catch (e: IOException) {
            e.printStackTrace()
            binding.webServerStatusTextView.text = "Web服务器启动失败: 端口被占用或无法绑定"
            Toast.makeText(context, "Web服务器启动失败: 端口被占用或无法绑定", Toast.LENGTH_LONG).show()
            // Show persistent error notification
            notificationHelper.showErrorNotification("WebServer", "端口被占用或无法绑定", e)
        } catch (e: SecurityException) {
            e.printStackTrace()
            binding.webServerStatusTextView.text = "Web服务器启动失败: 安全权限错误"
            Toast.makeText(context, "Web服务器启动失败: 安全权限错误", Toast.LENGTH_LONG).show()
            // Show persistent error notification
            notificationHelper.showErrorNotification("WebServer", "安全权限错误", e)
        } catch (e: Exception) {
            e.printStackTrace()
            binding.webServerStatusTextView.text = "Web服务器启动失败: ${e.message}"
            Toast.makeText(context, "Web服务器启动失败: ${e.message}", Toast.LENGTH_LONG).show()
            // Show persistent error notification
            notificationHelper.showErrorNotification("WebServer", e.message ?: "未知错误", e)
        }
    }

    private fun updateServerStatusDisplay() {
        val context = context ?: return
        
        try {
            // 获取设备的WiFi管理器
            val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
            
            // 获取并格式化IP地址
            val formattedIpAddress: String
            
            // 尝试获取WiFi IP地址（如果可用）
            if (wifiManager.isWifiEnabled) {
                val wifiInfo = wifiManager.connectionInfo
                val ipAddress = wifiInfo.ipAddress
                formattedIpAddress = if (ipAddress == 0) {
                    "127.0.0.1"
                } else {
                    Formatter.formatIpAddress(ipAddress)
                }
            } else {
                // 如果WiFi未启用，使用本地回环地址
                formattedIpAddress = "127.0.0.1"
            }
            
            // 显示Web服务器信息，并提供本地访问选项
            val statusText = StringBuilder()
            statusText.append("Web服务器运行中\n")
            statusText.append("请在浏览器中访问:\n")
            statusText.append("- 本机: http://127.0.0.1:$SERVER_PORT\n")
            
            // 如果有WiFi IP地址，也显示出来
            if (formattedIpAddress != "127.0.0.1") {
                statusText.append("- WiFi网络: http://$formattedIpAddress:$SERVER_PORT\n")
            }
            
            // 添加提示信息
            statusText.append("\n提示: 即使未连接WiFi，也可以在本机访问")
            
            binding.webServerStatusTextView.text = statusText.toString()
        } catch (e: SecurityException) {
            e.printStackTrace()
            binding.webServerStatusTextView.text = "获取网络信息失败: 安全权限错误\n请尝试使用: http://127.0.0.1:$SERVER_PORT"
            // Show persistent error notification
            notificationHelper.showErrorNotification("WiFiStatus", "安全权限错误", e)
        } catch (e: Exception) {
            e.printStackTrace()
            binding.webServerStatusTextView.text = "获取网络信息失败: ${e.message}\n请尝试使用: http://127.0.0.1:$SERVER_PORT"
            // Show persistent error notification
            notificationHelper.showErrorNotification("WiFiStatus", e.message ?: "未知错误", e)
        }
    }

    /**
     * 初始化RecyclerView
     */
    private fun initRecyclerView() {
        smsList = mutableListOf()
        smsAdapter = SmsAdapter(smsList)

        binding.smsRecyclerView.apply {
            layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
            adapter = smsAdapter
            setHasFixedSize(true)
        }
    }

    /**
     * 检查是否有读取短信的权限
     */
    private fun hasSmsPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            requireContext(),
            Manifest.permission.READ_SMS
        ) == PackageManager.PERMISSION_GRANTED
    }

    /**
     * 检查是否有发送通知的权限（Android 13+需要）
     */
    private fun hasNotificationPermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ContextCompat.checkSelfPermission(
                requireContext(),
                Manifest.permission.POST_NOTIFICATIONS
            ) == PackageManager.PERMISSION_GRANTED
        } else {
            // Android 13以下版本不需要显式请求通知权限
            true
        }
    }

    /**
     * 请求发送通知的权限
     */
    private fun requestNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !hasNotificationPermission()) {
            ActivityCompat.requestPermissions(
                requireActivity(),
                arrayOf(Manifest.permission.POST_NOTIFICATIONS),
                POST_NOTIFICATIONS_PERMISSION_REQUEST_CODE
            )
        }
    }

    /**
     * 请求读取短信的权限
     */
    private fun requestSmsPermission() {
        if (!hasSmsPermission()) {
            ActivityCompat.requestPermissions(
                requireActivity(),
                arrayOf(Manifest.permission.READ_SMS),
                READ_SMS_PERMISSION_REQUEST_CODE
            )
        } else {
            // 检查是否为MIUI系统
            if (MIUIPermissionHelper.isMIUI()) {
                // MIUI系统即使有了权限也可能需要特殊处理
                Toast.makeText(context, "您已拥有读取短信权限，正在加载短信...", Toast.LENGTH_SHORT).show()
                // 显示MIUI系统特定的权限确认对话框
                showMIUIPermissionConfirmDialog()
            } else {
                Toast.makeText(context, "您已拥有读取短信权限", Toast.LENGTH_SHORT).show()
            }
            loadSmsMessages()
        }
    }

    /**
     * 显示MIUI系统特定的权限确认对话框
     */
    private fun showMIUIPermissionConfirmDialog() {
        if (!MIUIPermissionHelper.isMIUI()) {
            return
        }
        
        try {
            val miuiVersion = MIUIPermissionHelper.getMIUIVersion()
            val message = "MIUI系统需要额外设置才能正常读取短信：\n\n" +
                    "1. 确保已在系统设置中授予短信读取权限\n" +
                    "2. 请在应用权限设置中开启所有相关权限\n" +
                    "3. 如果仍无法读取短信，请重启应用后再试"
            
            android.app.AlertDialog.Builder(requireContext())
                .setTitle("MIUI权限确认")
                .setMessage(message)
                .setPositiveButton("我已确认") { _, _ ->
                    // 确认后尝试加载短信
                    loadSmsMessages()
                }
                .setNeutralButton("去系统设置") { _, _ ->
                    // 跳转到应用详情页
                    val intent = android.content.Intent(
                        android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                    )
                    intent.data = Uri.fromParts("package", requireContext().packageName, null)
                    startActivity(intent)
                }
                .show()
        } catch (e: Exception) {
            Log.e("FirstFragment", "显示MIUI权限确认对话框失败: ${e.message}")
        }
    }

    /**
     * 加载短信消息
     */
    private fun loadSmsMessages() {
        smsList.clear()

        val contentResolver: ContentResolver = requireContext().contentResolver
        val uri: Uri = Telephony.Sms.CONTENT_URI

        // 定义要查询的列
        val projection = arrayOf(
            Telephony.Sms._ID,       // 短信ID
            Telephony.Sms.ADDRESS,   // 发送者号码
            Telephony.Sms.BODY,      // 短信内容
            Telephony.Sms.DATE,      // 短信时间戳
            Telephony.Sms.READ       // 是否已读
        )

        // 查询短信，按日期降序排列，取前10条
        val sortOrder = "${Telephony.Sms.DATE} DESC LIMIT 100"

        try {
            val cursor: Cursor? = contentResolver.query(
                uri,
                projection,
                null,
                null,
                sortOrder
            )

            cursor?.use { c ->
                val idColumn = c.getColumnIndexOrThrow(Telephony.Sms._ID)
                val addressColumn = c.getColumnIndexOrThrow(Telephony.Sms.ADDRESS)
                val bodyColumn = c.getColumnIndexOrThrow(Telephony.Sms.BODY)
                val dateColumn = c.getColumnIndexOrThrow(Telephony.Sms.DATE)
                val readColumn = c.getColumnIndexOrThrow(Telephony.Sms.READ)

                while (c.moveToNext()) {
                    val id = c.getString(idColumn)
                    val address = c.getString(addressColumn)
                    val body = c.getString(bodyColumn)
                    val date = c.getLong(dateColumn)
                    val read = c.getInt(readColumn)

                    smsList.add(SmsMessage(id, address, body, date, read))
                }
            }

            // 通知适配器数据已更新
            smsAdapter.notifyDataSetChanged()

            // 将短信数据传递给Web服务器
            println("FirstFragment: 加载了\${smsList.size}条短信，准备传递给WebServer")
            webServer?.setSmsMessages(smsList)
            if (webServer == null) {
                println("FirstFragment: 警告 - WebServer实例为空，无法传递短信数据")
            }

            if (smsList.isEmpty()) {
                // 对于MIUI系统，可能需要特殊提示
                if (MIUIPermissionHelper.isMIUI()) {
                    Toast.makeText(context, "未找到短信，MIUI系统可能需要额外设置", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(context, "未找到短信", Toast.LENGTH_SHORT).show()
                }
            } else {
                Toast.makeText(context, "已加载${smsList.size}条短信", Toast.LENGTH_SHORT).show()
            }

        } catch (e: Exception) {
            Log.e("FirstFragment", "加载短信失败: ${e.message}")
            // 对于MIUI系统，提供更具体的错误处理
            if (MIUIPermissionHelper.isMIUI()) {
                Toast.makeText(context, "MIUI系统加载短信失败，请检查权限设置", Toast.LENGTH_SHORT).show()
                notificationHelper.showErrorNotification("SMSLoading", "MIUI系统加载短信失败，请检查权限设置", e)
            } else {
                Toast.makeText(context, "加载短信失败: ${e.message}", Toast.LENGTH_SHORT).show()
                notificationHelper.showErrorNotification("SMSLoading", e.message ?: "加载短信失败", e)
            }
        }
    }

    /**
     * 处理权限请求结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        if (requestCode == READ_SMS_PERMISSION_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，可以加载短信
                if (MIUIPermissionHelper.isMIUI()) {
                    // MIUI系统即使授予了权限也需要额外引导
                    showMIUIPermissionConfirmDialog()
                } else {
                    loadSmsMessages()
                }
            } else {
                // 权限被拒绝
                if (MIUIPermissionHelper.isMIUI()) {
                    Toast.makeText(context, "需要读取短信权限才能显示短信列表，MIUI系统请在设置中开启所有相关权限", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(context, "需要读取短信权限才能显示短信列表", Toast.LENGTH_SHORT).show()
                }
            }
        } else if (requestCode == POST_NOTIFICATIONS_PERMISSION_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 通知权限被授予
                Toast.makeText(context, "通知权限已授予", Toast.LENGTH_SHORT).show()
            } else {
                // 通知权限被拒绝
                Toast.makeText(context, "未授予通知权限，将无法收到消息刷新通知", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onDestroy() {
        super.onDestroy()
        // 停止Web服务器
        webServer?.stopServer()
    }

    /**
     * 实现SmsRefreshCallback接口的方法
     * 当WebServer触发刷新时调用此方法，实际加载新的短信数据
     */
    override fun onRefreshSmsMessages() {
        requireActivity().runOnUiThread {
            if (hasSmsPermission()) {
                println("FirstFragment: WebServer触发短信刷新")
                loadSmsMessages()
            } else {
                println("FirstFragment: 没有短信权限，无法刷新消息")
            }
        }
    }
    
    /**
     * 使用SMTP协议自动发送邮件，包含最近的10条短信
     * 
     * 此方法已更新为使用WorkManager调度邮件发送任务，无需用户交互确认，
     * 并将设备上最近收到的10条短信包含在邮件内容中。
     * 根据不同的SIM卡选择不同的收件人邮箱。
     */
    fun sendEmailWithSmtp(simInfo: String) {
        try {
            // 确保在发送邮件前重新加载最新的短信数据
            val recentMessages = synchronized(this) {
                // 先在后台线程中获取内容解析器
                val contentResolver = requireContext().contentResolver
                val uri: Uri = Telephony.Sms.CONTENT_URI
                
                // 定义要查询的列
                val projection = arrayOf(
                    Telephony.Sms._ID,       // 短信ID
                    Telephony.Sms.ADDRESS,   // 发送者号码
                    Telephony.Sms.BODY,      // 短信内容
                    Telephony.Sms.DATE,      // 短信时间戳
                    Telephony.Sms.READ       // 是否已读
                )
                
                // 查询短信，按日期降序排列，取前10条
                val sortOrder = "${Telephony.Sms.DATE} DESC LIMIT 10"
                
                val messagesToSend = ArrayList<SmsMessage>()
                
                try {
                    val cursor: Cursor? = contentResolver.query(
                        uri,
                        projection,
                        null,
                        null,
                        sortOrder
                    )
                    
                    cursor?.use {
                        val idColumn = it.getColumnIndexOrThrow(Telephony.Sms._ID)
                        val addressColumn = it.getColumnIndexOrThrow(Telephony.Sms.ADDRESS)
                        val bodyColumn = it.getColumnIndexOrThrow(Telephony.Sms.BODY)
                        val dateColumn = it.getColumnIndexOrThrow(Telephony.Sms.DATE)
                        val readColumn = it.getColumnIndexOrThrow(Telephony.Sms.READ)
                        
                        while (it.moveToNext()) {
                            val id = it.getString(idColumn)
                            val address = it.getString(addressColumn)
                            val body = it.getString(bodyColumn)
                            val date = it.getLong(dateColumn)
                            val read = it.getInt(readColumn)
                            
                            messagesToSend.add(SmsMessage(id, address, body, date, read))
                        }
                    }
                    
                    // 同步更新UI线程的smsList
                    Handler(Looper.getMainLooper()).post {
                        smsList.clear()
                        smsList.addAll(messagesToSend)
                        smsAdapter.notifyDataSetChanged()
                    }
                } catch (e: Exception) {
                    Log.e("FirstFragment", "发送邮件前加载最新短信失败: ${e.message}")
                }
                
                messagesToSend
            }
            
            // 如果没有获取到短信，尝试使用已有的smsList
            val messagesToUse = if (recentMessages.isEmpty()) {
                Log.w(TAG, "重新加载短信失败，尝试使用已有列表")
                val tempList = ArrayList<SmsMessage>()
                Handler(Looper.getMainLooper()).post {
                    val messages = if (smsList.size > 10) {
                        smsList.subList(0, 10)
                    } else {
                        smsList
                    }
                    tempList.addAll(messages)
                }
                // 等待UI线程处理完成
                Thread.sleep(300)
                tempList
            } else {
                recentMessages
            }
            
            if (messagesToUse.isEmpty()) {
                Log.e(TAG, "没有可发送的短信数据")
                Handler(Looper.getMainLooper()).post {
                    Toast.makeText(context, "没有可发送的短信数据", Toast.LENGTH_SHORT).show()
                }
                return
            }
            
            // 构建包含最近10条短信的邮件内容
            val emailContent = StringBuilder()
            emailContent.append("这是来自短信转发应用的邮件。\n\n")
            emailContent.append("短信来自 ${simInfo}\n\n")
            emailContent.append("以下是您设备上最近收到的${messagesToUse.size}条短信：\n\n")
            
            // 使用SimpleDateFormat格式化时间戳
            val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
            
            // 添加每条短信的详细信息
            for ((index, sms) in messagesToUse.withIndex()) {
                val formattedTime = dateFormat.format(Date(sms.date))
                emailContent.append("${index + 1}. 发件人: ${sms.address}\n")
                emailContent.append("   时间: $formattedTime\n")
                emailContent.append("   内容: ${sms.body}\n")
                emailContent.append("   ------\n\n")
            }
            
            emailContent.append("\n此邮件由应用自动发送，无需用户手动操作。")
            
            // 创建WorkRequest
            val workRequest: WorkRequest = OneTimeWorkRequestBuilder<SmsForwardWorker>()
                // 添加输入数据
                .setInputData(
                    androidx.work.Data.Builder()
                        .putString(SmsForwardWorker.KEY_SENDER, "批量转发")
                        .putString(SmsForwardWorker.KEY_CONTENT, emailContent.toString())
                        .putString(SmsForwardWorker.KEY_TIME, java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date()))
                        .putString(SmsForwardWorker.KEY_SIM_INFO, simInfo)
                        .build()
                )
                // 设置重试策略
                .setBackoffCriteria(
                    androidx.work.BackoffPolicy.EXPONENTIAL,
                    WorkRequest.MIN_BACKOFF_MILLIS,
                    TimeUnit.MILLISECONDS
                )
                .build()

            // 提交任务到WorkManager
            WorkManager.getInstance(requireContext()).enqueue(workRequest)
            Log.d(TAG, "批量邮件转发任务已调度，包含${messagesToUse.size}条短信")
            
            // 在UI线程显示成功提示
            Handler(Looper.getMainLooper()).post {
                Toast.makeText(context, "邮件发送任务已调度，包含${messagesToUse.size}条短信 (来自${simInfo})", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Log.e(TAG, "调度邮件发送失败: ${e.message}")
            // 在UI线程显示失败提示
            Handler(Looper.getMainLooper()).post {
                Toast.makeText(context, "邮件发送任务调度失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 使用com.android.email应用发送邮件（备用方法）
     * 
     * 注意：由于Android系统的安全限制，无法在没有用户确认的情况下自动发送邮件。
     * 本方法会预填充所有邮件信息，并打开邮件应用，用户只需点击"发送"按钮即可完成操作。
     */
    private fun sendEmailWithDefaultApp() {
        try {
            // 显示提示信息，告知用户接下来需要点击发送按钮
            Toast.makeText(context, "请在打开的邮件应用中点击'发送'按钮完成操作", Toast.LENGTH_LONG).show()
            
            // 创建邮件Intent，指定使用com.android.email应用
            val emailIntent = Intent(Intent.ACTION_SEND)
            emailIntent.type = "message/rfc822"
            emailIntent.`package` = "com.android.email" // 指定使用com.android.email应用
            
            // 设置邮件收件人、主题和正文
            emailIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf("a@qq.com"))
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, "短信转发应用消息")
            emailIntent.putExtra(Intent.EXTRA_TEXT, "这是来自短信转发应用的邮件。\n\n注意：此邮件由短信转发应用自动生成，请检查内容后点击发送。")
            
            // 添加标记表明这是自动生成的邮件，便于邮件应用识别
            emailIntent.putExtra("android.intent.extra.AUTO_SEND", true)
            
            // 检查com.android.email应用是否存在
            if (emailIntent.resolveActivity(requireActivity().packageManager) != null) {
                startActivity(emailIntent)
            } else {
                // 如果com.android.email不存在，回退到询问用户选择邮件应用
                val chooserIntent = Intent.createChooser(Intent(Intent.ACTION_SENDTO)
                    .setData(Uri.parse("mailto:a@qq.com"))
                    .putExtra(Intent.EXTRA_SUBJECT, "短信转发应用消息")
                    .putExtra(Intent.EXTRA_TEXT, "这是来自短信转发应用的邮件。\n\n注意：此邮件由短信转发应用自动生成，请检查内容后点击发送。")
                    .putExtra("android.intent.extra.AUTO_SEND", true), 
                    "选择邮件应用")
                startActivity(chooserIntent)
            }
        } catch (e: Exception) {
            Log.e(TAG, "发送邮件失败: ${e.message}")
            Toast.makeText(context, "发送邮件失败", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 模拟短信接收功能
     */
    private fun simulateSmsReception() {
        try {
            // 模拟短信数据
            val sender = "+8610086" // 模拟发送者号码
            val content = "这是一条测试短信，用于模拟短信接收功能。\n时间：" + 
                SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())
            val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())
            val simInfo = "模拟SIM卡信息"
            
            // 显示Toast提示
            Toast.makeText(context, "正在模拟接收短信...", Toast.LENGTH_SHORT).show()
            
            // 方式1：直接调度邮件转发任务（与SMSBroadcastReceiver相同的处理逻辑）
            val workRequest: WorkRequest = OneTimeWorkRequestBuilder<SmsForwardWorker>()
                .setInputData(
                    androidx.work.Data.Builder()
                        .putString(SmsForwardWorker.KEY_SENDER, sender)
                        .putString(SmsForwardWorker.KEY_CONTENT, content)
                        .putString(SmsForwardWorker.KEY_TIME, time)
                        .putString(SmsForwardWorker.KEY_SIM_INFO, simInfo)
                        .build()
                )
                .setBackoffCriteria(
                    androidx.work.BackoffPolicy.EXPONENTIAL,
                    WorkRequest.MIN_BACKOFF_MILLIS,
                    TimeUnit.MILLISECONDS
                )
                .build()
            
            // 提交任务到WorkManager
            WorkManager.getInstance(requireContext()).enqueue(workRequest)
            Log.d(TAG, "已模拟短信接收并调度邮件转发任务")
            
            // 方式2：创建模拟短信并添加到列表显示（如果有权限）
            if (hasSmsPermission()) {
                // 创建模拟短信对象
                val simulatedSms = SmsMessage(
                    "sim_" + System.currentTimeMillis().toString(), // 模拟ID
                    sender,
                    content,
                    System.currentTimeMillis(),
                    0 // 未读
                )
                
                // 添加到短信列表并更新UI
                requireActivity().runOnUiThread {
                    smsList.add(0, simulatedSms) // 添加到列表顶部
                    smsAdapter.notifyItemInserted(0)
                    binding.smsRecyclerView.scrollToPosition(0) // 滚动到顶部
                    
                    // 更新Web服务器数据
                    webServer?.setSmsMessages(smsList)
                }
            }
            
            Toast.makeText(context, "短信模拟成功，已触发转发流程", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Log.e(TAG, "模拟短信接收失败: ${e.message}")
            Toast.makeText(context, "模拟短信接收失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
}